package com.maistars.spider.service.process.html;

import com.alibaba.fastjson.JSONObject;
import com.maistars.spider.service.domain.rule.FieldRule;
import com.maistars.spider.service.process.html.jsoup.ExtractProcessor;
import com.maistars.spider.service.process.html.jsoup.HtmlBeginProcessor;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dhr
 * @date 2021/2/6 下午11:01
 */
@Data
public class HtmlProcessorPipeline {

    private Map<String,Object> htmlProcessorContext = new HashMap<>();

    private List<HtmlProcessor> htmlProcessors = new ArrayList<>();

    private HtmlProcessorConfig htmlProcessorConfig;

    public HtmlProcessorPipeline(String config){
        this.htmlProcessorConfig = new HtmlProcessorConfig(config);
    }

    public HtmlProcessorPipeline(JSONObject processorConfig){
        this.htmlProcessorConfig = new HtmlProcessorConfig(processorConfig);
    }

    public List<String> execute() {
        List<String> contents = new ArrayList<>();
        htmlProcessors.stream().forEach(processor->{
            processor.process(contents);
        });
        return contents;
    }

    public static HtmlProcessorPipeline build(int type, JSONObject processorConfig, FieldRule fieldRule, String htmlContent) {
        HtmlProcessorPipeline htmlProcessorPipeline = new HtmlProcessorPipeline(processorConfig);
        // 走Jsoup解析引擎
        if (type == 0) {
            htmlProcessorPipeline.htmlProcessors.add(new HtmlBeginProcessor(htmlContent,fieldRule,htmlProcessorPipeline.htmlProcessorConfig,htmlProcessorPipeline.htmlProcessorContext).init());
            htmlProcessorPipeline.htmlProcessors.add(new ExtractProcessor(htmlContent,fieldRule,htmlProcessorPipeline.htmlProcessorConfig,htmlProcessorPipeline.htmlProcessorContext).init());
        }
        return htmlProcessorPipeline;
    }

}
